"""
异步数据库连接和会话管理
"""
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import MetaData
from typing import AsyncGenerator
from loguru import logger

from app.core.config import settings

 # 创建异步数据库引擎（MySQL）
async_engine = create_async_engine(
    settings.database_async_url,
    pool_pre_ping=True,
    pool_recycle=300,
    echo=settings.DEBUG,
    future=True
)

 # 创建异步会话工厂
AsyncSessionLocal = async_sessionmaker(
    async_engine,
    class_=AsyncSession,
    expire_on_commit=False
)

 # 已移除同步引擎和会话工厂

# 创建基础模型类
Base = declarative_base()

# 元数据对象，用于数据库迁移
metadata = MetaData()


async def get_async_db() -> AsyncGenerator[AsyncSession, None]:
    """
    获取异步数据库会话
    用作FastAPI的依赖注入
    """
    async with AsyncSessionLocal() as session:
        try:
            yield session
        finally:
            await session.close()
async def create_async_tables():
    """创建所有表（异步版本）"""
    async with async_engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)


async def drop_async_tables():
    """删除所有表（异步版本）"""
    async with async_engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)


async def init_db():
    """初始化数据库"""
    await create_async_tables()
    logger.info("数据库表创建成功")


async def close_db():
    """关闭数据库连接"""
    await async_engine.dispose()
    logger.info("数据库连接关闭")
